package youtube;

import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.ResourceId;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
import com.google.api.services.youtube.model.Thumbnail;

import com.google.gdata.client.*;
import com.google.gdata.client.youtube.*;
import com.google.gdata.data.*;
import com.google.gdata.data.geo.impl.*;
import com.google.gdata.data.media.*;
import com.google.gdata.data.media.mediarss.*;
import com.google.gdata.data.youtube.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

/**
 * this class get url of youtube trailer search results
 * @author chenji
 *
 */
public class Search {

	private static final long NUMBER_OF_VIDEOS_RETURNED = 1;

	private static YouTube youtube;

	public static String getUrl(String title) {

		try {
			youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
				public void initialize(HttpRequest request) throws IOException {
				}
			}).setApplicationName("search").build();

			String queryTerm = title + " official trailer";

			YouTube.Search.List search = youtube.search().list("id,snippet");

			String apiKey = "AIzaSyAX7xE_Kg3FASqBema_xFniy00ahZNlCOw";
			search.setKey(apiKey);
			search.setQ(queryTerm);

			search.setType("video");

			search.setFields("items(id/kind,id/videoId,snippet/title)");
			search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);

			SearchListResponse searchResponse = search.execute();
			List<SearchResult> searchResultList = searchResponse.getItems();
			if (searchResultList != null) {
				Iterator<SearchResult> it = searchResultList.iterator();
				if (it.hasNext()) {

					SearchResult singleVideo = it.next();
					ResourceId rId = singleVideo.getId();

					if (rId.getKind().equals("youtube#video")) {
						String url = "https://www.youtube.com/watch?v=" + rId.getVideoId();
						return url;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public static void main(String[] args) {
		YouTubeService service = new YouTubeService("", "");
	}
}
